package DEEPERsource.DEEPERsource.source.client;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import preprocessing.SimplePreprocessor;
import corpus.Abstract;
import corpus.Text;
import corpus.ppi.CorpusFactory;

public class FoldsBuilder {

	public void run() {
		CorpusFactory cFactory = new CorpusFactory();
		Text corpus = cFactory.getCorpusFromPPIXML("resource/aimed.xml",
				new SimplePreprocessor());
		// Text corpus = cFactory.getCorpusFromPPIXML("resource/test.xml", new
		// SimplePreprocessor());
		for (int k = 1; k < 11; k++) {
			File[] folds = (new File("resource/sparse/aimed/foldsMeta/" + k))
					.listFiles();
			Map<String, String> map = new HashMap<String, String>();
			for (File file : folds) {
				try {
					BufferedReader reader = new BufferedReader(new FileReader(file));
					String s;
					while ((s = reader.readLine()) != null) {
						map.put(s, file.getName());
					}
					reader.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			for (Iterator<Text> i = corpus.iterator(); i.hasNext();) {
				Text t = i.next();
				if (!(t instanceof Abstract)) {
					continue;
				}
				final String[] sp = t.id().split("\\|");
				String fold = map.get(sp[1]);
				File path = new File("resource/sparse/aimed");
				String[] list = path.list(new FilenameFilter() {
					public boolean accept(File dir, String name) {
						return name.startsWith(sp[0]+".");
					}
				});
				for (String fName : list) {
					FileInputStream from = null;
					FileOutputStream to = null;
					try {
						File f = new File("resource/sparse/aimed/folds/"+k+"/"+fold);
						if(!f.exists()){
							f.mkdirs();
						}
						from = new FileInputStream("resource/sparse/aimed/" + fName);
						to = new FileOutputStream("resource/sparse/aimed/folds/" + k + "/" + fold + "/" + fName);
						byte[] buffer = new byte[4096];
						int bytesRead;
						while ((bytesRead = from.read(buffer)) != -1)
							to.write(buffer, 0, bytesRead); // write
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if (from != null)
							try {
								from.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						if (to != null)
							try {
								to.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
					}
				}
			}
		}
	}

	public static void main(String[] args) {
		(new FoldsBuilder()).run();
	}
}
